<!-- 活动分享配置模块 -->
<template>
  <div>
    <a-form
      ref="activityAwardListFormRef"
      class="form"
      layout="vertical"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }" 
      :model="activityDetailInfo.activityAwardList"
      :rules="props.isDetail ? [] : formRules"
      :scrollToFirstError="true"
    >
      <a-form-item v-for="(item, index) in awardConfig" :key="index" name="activityAwardList">
        <template #label>
          <div>
            <span>{{ item.labelName ? item.labelName : (item.awardRemark ? (item.awardRemark + '奖品清单') : '奖品清单') }}</span>
            <a-button :disabled="props.isDetail" type="link" @click="bindAward(item.awardRemark,item.awardType,item.awardMaxNum)">新建奖品</a-button>
          </div>
        </template>
        <a-table :scroll="{ x: 10 }" :dataSource="item.awardRemark ? activityDetailInfo.activityAwardList.filter(_=>_.remark === item.awardRemark) : activityDetailInfo.activityAwardList" :columns="awardTableColums" :pagination="false" size="small">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'awardType'">
              <template v-if="record.awardType === 0">微信代金券</template>
              <template v-if="record.awardType === 1">实物</template>
              <template v-if="record.awardType === 2">虚拟券</template>
              <template v-if="record.awardType === 3">福分</template>
            </template>
            <template v-if="column.key === 'awardPrice'">
              <span>{{ record.awardPrice ? record.awardPrice / 100 : '--' }}</span>
            </template>
            <template v-if="column.key === 'exchangeShareNum'">
              <span>{{ record.exchangeShareNum || '--' }}</span>
            </template>
            <template v-if="column.key === 'awardProbability'">
              <template v-if="record.awardLevel === 0">所有的空奖都改为安慰奖</template>
              <template v-else>{{ Number(record.awardProbability) / 100 }}%</template>
            </template>
            <template v-if="column.key === 'awardLevel'">
              <template v-if="record.awardLevel === 0">安慰奖</template>
              <template v-if="record.awardLevel === 1">一等奖</template>
              <template v-if="record.awardLevel === 2">二等奖</template>
              <template v-if="record.awardLevel === 3">三等奖</template>
            </template>
            <template v-if="column.key === 'op'">
              <a-button :disabled="props.isDetail" type="link" danger @click="deleteSelectAward(record)">删除</a-button>
              <a-button type="link" @click="lookAwardDetail(record)">查看</a-button>
            </template>
          </template>
        </a-table>
      </a-form-item>
    </a-form>

    <!-- 新增奖品弹窗 -->
    <AddAwardModal ref="addAwardModalRef" />
    <!-- 奖品详情 -->
    <CouponDetail ref="couponDetailRef" />
    <!-- 实物奖品详情 -->
    <GoodsDetail ref="goodsDetailRef" />
    <!-- 福分奖品详情 -->
    <ScoreDetail ref="scoreDetailRef" />
  </div>
</template>

<script lang="ts" setup>
import { defineProps, computed, reactive, ref, defineExpose, getCurrentInstance, onMounted, inject } from 'vue'
import AddAwardModal from './AddAwardModal.vue'
import CouponDetail from '@/views/award/coupon/Detail.vue'
import GoodsDetail from '@/views/award/goods/Detail.vue'
import ScoreDetail from '@/views/award/score/Detail.vue'

const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
const couponDetailRef = ref()
const goodsDetailRef = ref()
const scoreDetailRef = ref()
// 接收父组件的创建活动的详细参数
let activityDetailInfoInject: any = inject('activityDetailInfo')
let activityDetailInfo: any = activityDetailInfoInject.value
// 接收父组件的活动模板申请数据
let activityTemplateDataRef : any = inject('activityTemplateData')
let activityTemplateData : any = activityTemplateDataRef.value
const props = defineProps({
  // 是否是详情
  isDetail: {
    type: Boolean,
    default: false
  },
  // 奖品要求 部分活动需要备注则需要多个table列 此时类型为数组 默认是一项 为对象
  awardConfig: {
    type: Array,
    default: () => []
  },
  // awardConfig与下面单个属性都存在时以awardConfig为准
  // 奖品最大数量默认1个 
  awardMaxNum: {
    type: Number,
    default: 1,
  },
  // 奖品最小数量 默认1个
  awardMinNum: {
    type: Number,
    default: 1,
  },
  // 奖品类型 0: 微信代金券 1: 实物 2: 虚拟券 3: 福分 默认允许绑定所有类型
  awardType: {
    type: String,
    default: '0,1,2,3'
  },
  // 奖品备注 部分活动绑定卡券奖品时需要填写备注；例如【越减越便宜】活动的ABC卡券奖品...['A','B','C']
  awardRemark: {
    type: [String, Object],
    default: null
  }
})

const formRules = ref({
  activityAwardList: [{ required: true }]
})

// 表单实例
const activityAwardListFormRef = ref()
// 新增奖品弹窗实例
const addAwardModalRef = ref()

// 奖品清单
const awardTableColums = reactive([
  { title:'奖品名称', dataIndex: 'awardName', key: 'awardName', fixed: 'left', width: 100 },
  { title:'奖品编号', dataIndex: 'awardId', key: 'awardId', width: 100 },
  { title:'奖品类型', dataIndex: 'awardType', key: 'awardType', width: 100 },
  { title:'奖品数量', dataIndex: 'awardNum', key: 'awardNum', width: 100 },
  { title:'奖品价值', dataIndex: 'awardPrice', key: 'awardPrice', width: 100 },
  { title:'操作', dataIndex: 'op', key: 'op', width: 100, align: 'center', fixed: 'right' },
])


// 处理奖品配置信息
const awardConfig = computed(() => {
  // 处理奖品配置信息
  // 校验是否传递了配置信息
  if(props.awardConfig.length === 0){ // 未传递配置信息 合并单个配置到奖品配置信息
    return [{ awardMaxNum: props.awardMaxNum, awardMinNum: props.awardMinNum, awardType: props.awardType, awardRemark: props.awardRemark }]
  }else{
    return props.awardConfig
  }
})

onMounted(() => {
  if(activityTemplateData.activityTemplateNo === 'ACTE001' || activityTemplateData.activityTemplateNo === 'ACTE008'){
    awardTableColums.splice(5,0,{ title:'奖品等级', dataIndex: 'awardLevel', key: 'awardLevel', width: 100 })
    awardTableColums.splice(6,0,{ title:'中奖概率', dataIndex: 'awardProbability', key: 'awardProbability', width: 100 })
  }
  // 奖品兑换所需积分
  if(activityTemplateData.activityTemplateNo === 'ACTE024'){
    awardTableColums.splice(-1,0,{ title:'奖品兑换所需积分', dataIndex: 'exchangeShareNum', key: 'exchangeShareNum', width: 100 })
  }
})

/**
 * 新增奖品
 */
function bindAward(remark, awardType, awardMaxNum){
  addAwardModalRef.value.show(remark, awardType, awardMaxNum)
}
/**
 * 删除已绑定奖品
 */
function deleteSelectAward(record) {
  activityDetailInfo.activityAwardList = activityDetailInfo.activityAwardList.filter(item => !(item.awardId === record.awardId && item.awardType === record.awardType))
}

// 表单校验事件
async function validateFields(isDraft) {
  return new Promise((resolve,reject) => {
    // 如果是详情页不做校验
    if(props.isDetail){
      resolve()
      return
    }
    // 如果是保存草稿 不校验
    if(isDraft){
      resolve()
      return
    }
    // 判断是多个还是单个
    if(awardConfig.value?.length > 1){  // 多个奖品 保证绑定数量和奖品数量一致
      const awardTotalNum = awardConfig.value.reduce((total, item) => total + item.awardMaxNum, 0)
      if(activityDetailInfo.activityAwardList?.length === awardTotalNum){
        resolve()
        return
      }else{
        reject('请完成卡券绑定')
        return
      }
    }else{  // 单个奖品 保证奖品有值(保证奖品数量大于等于最小值) 并且如果有中奖概率的话 保证总中奖率是100%
      if(activityDetailInfo.activityAwardList.length < props.awardMinNum){
        reject(`奖品数量不能少于${props.awardMinNum}个`)
        return
      }else{
        if((activityTemplateData.activityTemplateNo === 'ACTE001' || activityTemplateData.activityTemplateNo === 'ACTE008') && activityDetailInfo.activityAwardList.reduce((total, item) => total + item.awardProbability, 0) !== 10000){
          reject('奖品中奖概率总和必须为100%，请重新设置中奖概率')
          return
        }
        resolve()
        return
      }
    }
  })
}
// 表单重置事件
function clearValidate() {
  if(activityAwardListFormRef.value !== undefined){
    activityAwardListFormRef.value.clearValidate()
  }
}
// 查看奖品详情
function lookAwardDetail(record) {
  // 根据奖品类型查看奖品详情
  if(record.awardType === 0){ // 微信代金券
    couponDetailRef.value.show(record.awardId)
  }else if(record.awardType === 1){ // 实物奖品
    goodsDetailRef.value.show(record.awardId)
  }else if(record.awardType === 2){ // 虚拟券
    $infoBox.message.warn('虚拟券奖品详情暂未实现')
  }else if(record.awardType === 3){ // 福分
    scoreDetailRef.value.show(record.awardId)
  }
}

// 暴露表单校验事件
defineExpose({
  validateFields,
  clearValidate
})

</script>

<style lang="less" scoped>
.form{
  margin-left: 20px;
  margin-top: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number){
  width: 100%;
}
:deep(.ant-table-wrapper){
  margin: 0;
}
</style>